package data.generators;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Map;

import data.DataConstructor;
import data.DataGenerator;
import data.DataStorage;
import data.Game;
import data.Player;
import data.DataGatherer;
import db.DBCommunicator;
import exceptions.IdentifierException;
import exceptions.DataException;

public class DBDataGenerator implements DataGenerator{
	private String player1column;
	private String player1scoreColumn;
	private String player2column;
	private String player2scoreColumn;
	private String gameIDColumn;
	private String gameEnvironmentColumn;
	private String gamesTableName;
	private String dbName;
	private DataConstructor dataGatherer;
	public DBDataGenerator(String player1column, String player2column, String gameIDColumn,
			String player1scoreColumn, String player2scoreColumn,
			String gameEnvironmentColumn, String gamesTableName, String dbName) {
		this.player1column = player1column;
		this.player2column = player2column;
		this.player1scoreColumn = player1scoreColumn;
		this.player2scoreColumn = player2scoreColumn;
		this.gameIDColumn = gameIDColumn;
		this.gameEnvironmentColumn = gameEnvironmentColumn;
		this.gamesTableName = gamesTableName;
		this.dbName = dbName;
		this.dataGatherer = new DataGatherer();
		generateData();
	}
	public void generateData(){
		Connection connection = DBCommunicator.getConnection(dbName);
		getGames(connection);
		DBCommunicator.flush();
	}

	
	private static final String GAME_QUERY = "SELECT * FROM ";
	private String getGamesQuery(){
		return GAME_QUERY + gamesTableName;
	}
	private void getGames(Connection connection){
		try {
			Statement s = connection.createStatement();
			s.executeQuery(getGamesQuery());
			ResultSet resultSet = s.getResultSet();
			String player1name;
			int player1score;
			String player2name;
			int player2score;
			int gameID;
			String environment;
			while (resultSet.next()){
				gameID = resultSet.getInt(gameIDColumn);
				player1name = resultSet.getString(player1column);
				player1score = resultSet.getInt(player1scoreColumn);
				player2name = resultSet.getString(player2column);
				player2score = resultSet.getInt(player2scoreColumn);
				environment = resultSet.getString(gameEnvironmentColumn);
				try {
					//Cheating with the game ID.
					dataGatherer.addGame(new Game(dataGatherer.addPlayer(player1name,player1name.hashCode()), dataGatherer.addPlayer(player2name,player2name.hashCode()), player1score, player2score, gameID, environment));
				} catch (DataException e) {
					e.printStackTrace();
				} catch (IdentifierException e) {
					e.printStackTrace();
				}
			}
			s.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	@Override
	public DataStorage getDataStorage() {
		return dataGatherer.getDataStorage();
	}
	

}
